package model;

import java.sql.ResultSet;

import core.PgSQL;

public class UserGroup {
	protected int groupid;
	protected String groupname;
	protected int permission;
	
	public int getGroupId() {
		return groupid;
	}
	
	public void setGroupId(int groupid) {
		this.groupid = groupid;
	}
	
	public String getGroupName() {
		return groupname;
	}
	
	public void setGroupName(String groupname) {
		this.groupname = groupname;
	}
	
	public int getPermission() {
		return permission;
	}
	
	public void setPermission(int permission) {
		this.permission = permission;
	}

	public static int ANSWER_QUESTION = 0x1;
	public static int ADD_QUESTION = 0x2;
	public static int EDIT_QUESTION = 0x4;
	public static int DELETE_QUESTION = 0x8;
	public static int ADD_PAPER = 0x10;
	public static int EDIT_PAPER = 0x20;
	public static int DELETE_PAPER = 0x40;
	public static int CHANGE_QUESTIONTYPE = 0x80;
	
	static int[] all_permissions = null;
	public static int[] getAllPermissions(){
		if(all_permissions == null){
			all_permissions = new int[8];
			all_permissions[0] = ANSWER_QUESTION;
			all_permissions[1] = ADD_QUESTION;
			all_permissions[2] = EDIT_QUESTION;
			all_permissions[3] = DELETE_QUESTION;
			all_permissions[4] = ADD_PAPER;
			all_permissions[5] = EDIT_PAPER;
			all_permissions[6] = DELETE_PAPER;
			all_permissions[7] = CHANGE_QUESTIONTYPE;
		}
		return all_permissions;
	}

	public boolean hasPermission(int permission){
		return (this.permission & permission) == permission;
	}
	
	public void attachPermission(int permission){
		this.permission |= permission;
	}
	
	public boolean isAdministrator(){
		return this.permission == 0xFFFFFFFF;
	}
	
	public static UserGroup fromDatabase(ResultSet rs){
		UserGroup g = new UserGroup();
		try{
			g.setGroupId(rs.getInt(1));
			g.setGroupName(rs.getString(2));
			g.setPermission(rs.getInt(3));
		}catch(Exception e){
			e.printStackTrace();
		}
		return g;
	}
	
	public static UserGroup fromId(int id){
		PgSQL db = PgSQL.getInstance();
		ResultSet rs = db.query("SELECT * FROM qz_usergroup WHERE groupid=" + id);
		try{
			if(rs.next()){
				return fromDatabase(rs);
			}else{
				return new UserGroup();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return null;
	}
}
